#include <stdio.h>

#include "nuclei_sdk_hal.h"
#include "nuclei_libopt.h"

#define ARR_SIZE 8
uint8_t uart0_send_buffer[ARR_SIZE]={ 0x71 ,0x72,0x73,0x74,0x75,0x76,0x77,0x78};
uint8_t uart0_receive_buffer1[ARR_SIZE]={0};

uint8_t uart0_send_n=0,uart0_receive_n=0,uart1_send_n=0,uart1_receive_n=0,state0=0,state1=0;

/*!
    \brief      memory compare function
    \param[in]  src: source data pointer
    \param[in]  dst: destination data pointer
    \param[in]  length: the compare data length
    \param[out] none
    \retval     ErrStatus : ERROR or SUCCESS
*/
ErrStatus memory_compare(uint8_t* src, uint8_t* dst, uint8_t length) 
{
    while(length--){
        if(*src++ != *dst++)
            return ERROR;
    }
    return SUCCESS;
}



void uart0_handler(void)
{
    if(uart_get_flag_txip(UART0)==1)
    {
        if(uart_get_txbusy(UART0)==0)
            uart_write(UART0,uart0_send_buffer[uart0_send_n++]);
    }
    else if(uart_get_flag_rxip(UART0)==2)
    {
        if(uart_get_rxbusy(UART0)==0)
            uart0_receive_buffer1[uart0_receive_n++]=uart_read(UART0);
    }
    if(ARR_SIZE == uart0_send_n)
        uart_disable_txint(UART0);
    if(ARR_SIZE == uart0_receive_n)
        uart_disable_rxint(UART0);
}


int main(void )
{
    __enable_irq();
	ECLIC_Register_IRQ(UART0_IRQn, ECLIC_NON_VECTOR_INTERRUPT,
                                    ECLIC_LEVEL_TRIGGER, 1, 1,
                                    uart0_handler);	

    uart_init(UART0, 115200,UART_BIT_LENGTH_8);
    uart_config_stopbit(UART0,UART_STOP_BIT_2);

    uart_set_rx_watermark(UART0,0);
    uart_set_tx_watermark(UART0,1);

    uart_enable_rxint(UART0);
    uart_enable_txint(UART0);
    
    while(uart0_receive_n<ARR_SIZE );
    while(uart0_send_n<ARR_SIZE );

    state0=memory_compare(uart0_send_buffer,uart0_receive_buffer1,ARR_SIZE);


    uart0_send_n =0;
    uart0_receive_n = 0;

    uart_init(UART0, 115200,UART_BIT_LENGTH_7);
    uart_config_stopbit(UART0,UART_STOP_BIT_0p5);

    uart_enable_txint(UART0);
    uart_enable_rxint(UART0);

   
    state1=memory_compare(uart0_receive_buffer1,uart0_send_buffer,ARR_SIZE);
    #ifdef CFG_SIMULATION
        pass_fail_simulation(state0&state1);
    #endif 

	// gpio init
	gd_eval_led_init(LED2);	// sf1 mini LED_D5

    if(state0&state1)
    {
    	// choose right func to drive LED.
//    	gd_eval_led_on(LED2);	// drive LED '+';
		gd_eval_led_off(LED2);		// drive LED '-';
    }
    else
    {
        while(1)
        {
            gd_eval_led_toggle(LED2);
            delay_1ms(500);
        }
    }

    while(1);
    
    return 0;
}
